package com.youthfilmic.yuejian.weixin.core;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

import com.youthfilmic.yuejian.conn.WeixinConn;
import net.sf.json.JSONObject;

public class WeixinSign {

    /**
     * 获取url的微信签名
     *
     * */
    public static WeixinSignBean sign(String url) {
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + TokenSystem.getTicketValue() +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        WeixinSignBean bean = new WeixinSignBean();
        bean.setAppId(WeixinConn.APP_ID);
        bean.setJsapi_ticket(TokenSystem.getTicketValue());
        bean.setNonceStr(nonce_str);
        bean.setSignature(signature);
        bean.setTimestamp(timestamp);
        bean.setUrl(url);
        return bean;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static void main(String[] args) {
        String jsapi_ticket = "jsapi_ticket";
        // 注意 URL 一定要动态获取，不能 hardcode
        String url = "http://example.com";
        WeixinSignBean bean = sign(url);
        System.out.println(JSONObject.fromObject(bean).toString());
    }
}
